#!/bin/bash
#使用说明，用来提示输入参数
usage() {
    echo "Usage: sh redis.sh [start|stop"
    exit 1
}
# redis主备服务安装路径
# ============= 环境变量 ===============
PORT="6381" # redis端口
OTHER_SERVER_IP="10.150.7.104" # 另一个redis机器IP
VIP="10.150.7.150" # keepalive虚拟IP
FLODER=/root/redis_master_backup/redis$PORT # redis程序目录
# ======================================

# 新建日志文件
function createLogFile(){
  if [ ! -f "$FLODER/redis.log" ]; then
    touch $FLODER/redis.log
  fi
}


# 重建主备关系
function setUpRedisRole() {
    if [ `ip addr | grep $VIP | wc -l` = 0 ]; then
        echo "重建主备关系：当前为备机"
        $FLODER/redis-cli -p $PORT slaveof $OTHER_SERVER_IP $PORT
    else
        echo "重建主备关系：当前为主机"
        $FLODER/redis-cli -p $PORT slaveof no one
    fi
}



#检查程序是否在运行
function is_exist(){
  pid=`ps -ef|grep $PORT|grep -v grep|awk '{print $2}'`
  #如果不存在返回1，存在返回0 
  if [[ "$pid" == "" ]]; then
    echo "$APP_NAME 未检测到运行进程"
    return 1;
  else
    return 0;
  fi
}

# 启动Redis服务，并建立主从关系
function startRedis () {
    is_exist
    if [ $? -eq 0 ]; then
        echo "redis：$PORT正在运行"
    else
        echo "redis：$PORT没有运行，开始启动"
        # 新建日志文件
        createLogFile
        # 启动redis服务
        $FLODER/redis-server $FLODER/redis.conf
        # 重建主从关系
        setUpRedisRole
        # 查看redis日志文件
        tail -f ./redis.log
    fi
# 建立主从关系
}

# 停止Redis
function stopRedis(){
    is_exist
    if [ $? -eq 0 ]; then
        kill -9 $pid
        echo "redis：$PORT 已停止，进程ID=${pid}"
    else
        echo "redis：$PORT没有运行"
    fi
}

#根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
    start)
        startRedis
    ;;
    stop)
        stopRedis
    ;;
    *)
        usage
    ;;
esac


# 103 104 主从目录结构
# /root/redis_master_backup/redis6381
# .
# ├── appendonly.aof
# ├── dump.rdb
# ├── redis-cli
# ├── redis.conf
# ├── redis.log
# ├── redis.pid
# ├── redis-server
# ├── redis-trib.rb
# └── temp-1229.rdb

# redis 主日志信息如下：
# 21515:M 04 Nov 2022 09:52:03.552 - 26 clients connected (1 replicas), 111689680 bytes in use
# 21515:M 04 Nov 2022 09:52:08.566 - DB 11: 1559 keys (16 volatile) in 2048 slots HT.
# 21515:M 04 Nov 2022 09:52:08.566 - 26 clients connected (1 replicas), 111689680 bytes in use
# 21515:M 04 Nov 2022 09:52:13.579 - DB 11: 1559 keys (16 volatile) in 2048 slots HT.
# 21515:M 04 Nov 2022 09:52:13.580 - 26 clients connected (1 replicas), 111689680 bytes in us

# redis 备日志信息如下：
# 21515:M 04 Nov 2022 09:52:03.552 - 26 clients connected (0 replicas), 111689680 bytes in use
# 21515:M 04 Nov 2022 09:52:08.566 - DB 11: 1559 keys (16 volatile) in 2048 slots HT.
# 21515:M 04 Nov 2022 09:52:08.566 - 26 clients connected (0 replicas), 111689680 bytes in use
# 21515:M 04 Nov 2022 09:52:13.579 - DB 11: 1559 keys (16 volatile) in 2048 slots HT.
# 21515:M 04 Nov 2022 09:52:13.580 - 26 clients connected (0 replicas), 111689680 bytes in us
